<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="请输入机器人名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-refresh" @click="refresh">
        刷新
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="机器编号" prop="id" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="MAC地址" align="center">
        <template slot-scope="{row}">
          <span>{{ row.mac }}</span>
        </template>
      </el-table-column>
      <el-table-column label="机器人IP" align="center">
        <template slot-scope="{row}">
          <span>{{ row.ip }}</span>
        </template>
      </el-table-column>
      <el-table-column label="机器人名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="WIFI名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.wifiName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地图" align="center">
        <template slot-scope="{row}">
          <span>{{ row.mapValue }}</span>
        </template>
      </el-table-column>
      <el-table-column label="WIFI密码" align="center">
        <template slot-scope="{row}">
          <span>{{ row.wifiPassword }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="机器人状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.report | statusFilter">
            {{ row.report === 1 ? '在线':'离线' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button type="success" size="mini" @click="handleBind(row)">
            绑定地图
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item v-if="['update'].includes(dialogStatus)" label="机器人名称" prop="username">
          <el-input v-model="temp.name" placeholder="请输入机器人名称" />
        </el-form-item>
        <el-form-item v-if="['update'].includes(dialogStatus)" label="WIFI名称" prop="wifiName">
          <el-input v-model="temp.wifiName" placeholder="请输入WIFI名称" />
        </el-form-item>
        <el-form-item v-if="['update'].includes(dialogStatus)" label="WIFI密码" prop="wifPassword">
          <el-input v-model="temp.wifiPassword" placeholder="请输入WIFI密码" />
        </el-form-item>
        <el-form-item v-if="['bind'].includes(dialogStatus)" label="地图绑定" prop="bind">
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='bind'?bindData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, modifyRobotName, bindMapInfo } from '@/api/robot/robot-manager'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { validUsername, validPassword, validPhoneNum } from '@/utils/validate'
import { listMapAll } from '@/api/map/map'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'RobotManager',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        name: ''
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: [{ key: '1', text: '启用' }, { key: '0', text: '禁用' }],
      showReviewer: false,
      temp: {
        id: '',
        name: '',
        mac: '',
        ip: '',
        port: '',
        odom: '',
        wifiName: '',
        wifiPassword: '',
        mapId: ''
      },
      dialogFormVisible: false,
      dialogFormVisible1: true,
      dialogStatus: '',
      textMap: {
        update: '修改',
        bind: '绑定'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
      },
      downloadLoading: false,
      options: [],
      value: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getListMapAll: function() {
      listMapAll().then(response => {
        response.data.forEach((item) => {
          const name = (!item.name && typeof (item.name) !== 'undefined' && item.name !== 0) || item.name === '' ? '未命名' : item.name
          const option = {
            value: item.id,
            // eslint-disable-next-line no-undef,eqeqeq
            label: item.id + '--' + name
          }
          this.options.push(option)
        })
      })
    },
    getList() {
      this.listLoading = true
      listMapAll().then(response => {
        response.data.forEach((item) => {
          const name = (!item.name && typeof (item.name) !== 'undefined' && item.name !== 0) || item.name === '' ? '未命名' : item.name
          const option = {
            value: item.id,
            // eslint-disable-next-line no-undef,eqeqeq
            label: item.id + '--' + name
          }
          this.options.push(option)
        })
        listInfo(this.listQuery).then(response => {
          this.list = response.data.list
          this.total = response.data.total
          this.list.forEach((x, index) => {
            this.options.forEach((y) => {
              if (x.mapId === y.value) {
                x.mapValue = y.label
              }
            })
          })
        })
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    refresh() {
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '',
        name: '',
        mac: '',
        ip: '',
        port: '',
        odom: '',
        wifiName: '',
        wifiPassword: '',
        mapId: ''
      }
    },
    handleCreate() {
      this.rules = {
        username: [{ required: true, trigger: ['blur', 'change'], validator: validUsername }],
        phoneNum: [{ required: false, trigger: ['blur', 'change'], validator: validPhoneNum }],
        password: [{ required: true, trigger: ['blur', 'change'], validator: validPassword }]
      }
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.rules = {}
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleBind(row) {
      this.options = []
      this.rules = {}
      this.temp = Object.assign({}, row) // copy obj
      this.options = []
      this.value = this.temp.mapId
      this.getListMapAll()
      this.dialogStatus = 'bind'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.listLoading = true
          modifyRobotName(this.temp).then(() => {
            this.dialogFormVisible = false
            this.listLoading = false
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.$notify({
              title: '成功',
              message: '绑定成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    bindData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.listLoading = true
          const param = {
            robotId: this.temp.id,
            mapId: this.value
          }
          bindMapInfo(param).then(() => {
            this.dialogFormVisible = false
            this.listLoading = false
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.temp.mapId = this.value
            this.temp.mapValue = this.options.find((item) => {
              return item.value === this.value
            }).label
            this.list.splice(index, 1, this.temp)
            this.$notify({
              title: '成功',
              message: '绑定成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
